<template>
  <div class="full-height bg-white page-content content relative-position">
    <div style="padding: 0 20px 0">
      <div class="form-inline "
           style="justify-content: space-between; margin-top: 20px ;flex-basis: initial;padding: 0 ">
        <div class="left box" style="display: flex">
          <div class="row">
            <yz-input v-model.trim="queryParams.id"
                      class="margin-r-20"
                      :maxlength="20"
                      title="工单编号"/>
            <workshop-search v-model="queryParams" ref="workShopSearch" :isShift="false"/>
            <div class="margin-b-20 margin-r-20">
              <span class="name form-name" style="padding-right: 6px">报工时间:</span>
              <date-picker
                style="width: 240px"
                v-model="queryParams.timeRange"
                type="datetime"
                :showSecond="false"
                :showMinute="false"
                range
                placeholder="请选择报工时间"
                format="YYYY-MM-DD HH"
                :editable="false"
              />
            </div>
            <fuzzy-search
              v-model.trim="queryParams.productId"
              style="width: 240px"
              class="margin-r-20"
              isFilter
              title="产品名称"
              fuzzyValue="number"
              :fuzzyFunc="fuzzyFunPru"
            />
            <select-tooltip
              v-show="queryParams.productId !== null"
              v-model="queryParams.sort"
              isShowAll
              :options="processList"
              msg="加工工序"
            />
            <select-tooltip
              v-model="queryParams.status"
              :multiple="false"
              isShowAll
              :options="statusOptions"
              msg="接口反馈"
            />
          </div>
        </div>
        <div style="display: flex">
          <q-btn class="btn margin-r-10"
                 outline
                 color="primary"
                 label="重置"
                 @click="resetSearch" />
          <q-btn class="btn"
                 unelevated
                 @click="submit"
                 color="primary"
                 label="查询" />
        </div>
      </div>
      <div class="form-inline no-padding flex justify-between">
        <q-btn class="btn margin-r-20"
               outline
               color="primary"
               :disable="!selList.length"
               @click="updateData([])"
               label="更新" />
      </div>
    </div>
    <q-table color="primary"
             style="margin: 20px 20px 0"
             :data="tableData"
             :columns="columns"
             :loading="isTableLoading"
             row-key="id"
             class="myTable scroll stick-last-col"
             :pagination.sync="pagination"
             :hide-bottom="!!tableData.length"
             no-data-label="暂无数据"
             selection="multiple"
             :selected.sync="selList"
             ref="table">
      <template v-slot:header="props">
        <q-tr :props="props">
          <q-th
            v-for="col in props.cols"
            :key="col.name"
            :props="props"
            class="bor-b"
          >
            <q-checkbox v-model="props.selected" :disable="failNum === tableData.length" indeterminate-value="some" @input="selAll" v-if="col.name === 'workOrderGroupId'" />
            {{col.label}}
          </q-th>
        </q-tr>
      </template>
      <template v-slot:body="props">
        <q-tr :props="props">
          <q-td :props="props" class="bor-b font-size-14 " key="workOrderGroupId">
            <q-checkbox v-model="props.selected" :disable="props.row.state === 1" />
            {{ props.row.workOrderGroupId}}
          </q-td>
          <template v-for="col in props.cols">
            <q-td :props="props" class="bor-b font-size-14" v-if="col.name !== 'workOrderGroupId' && col.name !== 'state' && col.name !== 'operation' && col.name !== 'errorMsg'" :key="col.name">
              {{ props.row[col.name]}}
            </q-td>
          </template>
          <q-td :props="props" class="bor-b font-size-14 " key="state">
            <div style="min-width: 76px">
              <set-color :options="statusOptions" :colorType="props.row.state" />
            </div>
          </q-td>
          <q-td :props="props" class="bor-b font-size-14" key="errorMsg">
            {{ props.row.errorMsg}}
          </q-td>
          <q-td :props="props" class="bor-b font-size-14 " key="operation" style="width: 200px">
            <div>
              <q-btn flat
                     color="primary"
                     @click="updateData([props.row.id])"
                     :disable="props.row.state === 1"
                     class="table-flat-btn">
                更新
              </q-btn>
            </div>
          </q-td>
        </q-tr>
      </template>
    </q-table>
    <yz-pagination v-model="pagination" @onSearch="getList"/>
  </div>
</template>

<script>
import productStat from 'src/boot/statistics/product-stat'
import { getProcessList, getLogs, repushData } from 'src/boot/job/process-order'
import { mapGetters } from 'vuex'
import moment from 'moment'
import _ from 'lodash'

function getProductListNew (val) {
  return productStat.getSearchMaterials(val).then(res => {
    return Promise.resolve(res)
  })
}
export default {
  name: 'update-data',
  data () {
    return {
      fuzzyFunPru: getProductListNew,
      isTableLoading: false,
      processList: [],
      selList: [],
      // 表格分页配置
      pagination: {
        pageNum: 1, // 当前页码
        pageSize: 15, // 每页条数
        rowsNumber: 0 // 总条数
      },
      queryParams: {
        location: {
          id: null,
          level: null,
          label: '',
          hash: ''
        },
        devices: ['all'],
        id: '',
        productId: null,
        timeRange: [null, null],
        status: 'all',
        sort: ['all'],
        workshop: null,
        assetNumber: null,
        shift: 'all',
        workshopId: ''
      }, // 查询条件对象
      tableData: [], // 列表数据源
      failNum: 0,
      columns: [
        { name: 'workOrderGroupId', label: '工单编号', field: 'workOrderGroupId', align: 'left' },
        { name: 'productName', label: '加工产品', field: 'productName', align: 'left' },
        { name: 'processName', label: '加工工序', field: 'processName', align: 'left' },
        { name: 'orderNumber', label: '订单号', field: 'orderNumber', align: 'left' },
        { name: 'deviceName', label: '加工设备', field: 'deviceName', align: 'left' },
        { name: 'shiftName', label: '加工班次', field: 'shiftName', align: 'left' },
        { name: 'operatorName', label: '操作员', field: 'operatorName', align: 'left' },
        { name: 'workshopPlanningNumber', label: '计划编号', field: 'workshopPlanningNumber', align: 'left' },
        { name: 'checkinCount', label: '报工数量', field: 'checkinCount', align: 'left' },
        { name: 'reportTime', label: '报工时间', field: 'reportTime', align: 'left' },
        { name: 'state', label: '接口反馈', field: 'state', align: 'left' },
        { name: 'errorMsg', label: '错误信息', field: 'errorMsg', align: 'left' },
        { name: 'operation', field: 'operation', label: '操作', align: 'center' }
      ]
    }
  },
  mounted () {
    this.getWorkshops()
  },
  computed: {
    statusOptions () {
      return this.$getEnum(this.Enums.UPDATE_STATUS)
    },
    ...mapGetters(['userInfo'])
  },
  watch: {
    'queryParams.productId': {
      handler (val) {
        val !== null && this.getProcessList(val)
      },
      deep: true,
      immediate: true
    }
  },
  methods: {
    // 全选
    selAll () {
      let selList = []
      this.selList.forEach(item => {
        if (item.state + '' !== '1') {
          selList.push(item)
        }
      })
      this.selList = selList
    },
    getProcessList (id) {
      this.$q.loading.show()
      getProcessList([id]).then(res => {
        this.processList = res
      }).finally(() => {
        this.$q.loading.hide()
      })
    },
    getWorkshops () {
      this.$refs.workShopSearch.getWorkshops().then(() => {
        // this.routeFromName = ''
        this.getList()
      })
    },
    // 产品说了无失败反馈，不需考虑用户体验,所以无法检查是否为最后一条时返回第一页
    updateData (data) {
      let selList = []
      data.length ? (selList = data) : (selList = _.map(this.selList, 'id'))
      repushData(selList).finally(() => {
        this.getList()
      })
    },
    getList () {
      const params = {
        pageNum: this.pagination.pageNum,
        pageSize: this.pagination.pageSize
      }
      let since = _.isNil(this.queryParams.timeRange[0]) ? null : moment(this.queryParams.timeRange[0])
      let before = _.isNil(this.queryParams.timeRange[1]) ? null : moment(this.queryParams.timeRange[1])
      if (this.queryParams.productId !== null) {
        params['productId'] = this.queryParams.productId
        this.queryParams.sort[0] !== 'all' && (params['workingStepIds'] = this.queryParams.sort)
      }
      this.queryParams.id !== '' && (params['workOrderId'] = this.queryParams.id)
      this.queryParams.status !== 'all' && (params['state'] = this.queryParams.status)
      this.queryParams.devices[0] !== 'all' ? (params['devicesIds'] = this.queryParams.devices) : (params['workshopId'] = this.queryParams.location.id)
      let isOver = false
      if (since && before) {
        isOver = Math.abs(before.diff(since, 'days')) > 30
        if (isOver) {
          this.$message.warning('所选日期范围已超出30天')
        } else {
          params['startDate'] = since.format('YYYY-MM-DD HH:mm:ss')
          params['endDate'] = before.format('YYYY-MM-DD HH:mm:ss')
        }
      }
      if (!isOver) {
        this.$q.loading.show()
        this.isTableLoading = true
        getLogs(params).then(res => {
          res.list.forEach(o => {
            o.deviceName = `${this.$utils.label(o.deviceName)}(${this.$utils.label(o.deviceNumber)})`
            o.productName = `${this.$utils.label(o.productName)}(${this.$utils.label(o.productNumber)})`
            o.processName = `${o.processSort + 1}-${this.$utils.label(o.processName)}`
            o.checkinCount = this.$utils.label(o.checkinCount, 0)
            o.reportTime = o.reportTime ? this.$utils.formatDatetime(o.reportTime) : '--'
            o.errorMsg = o.state + '' === '1' ? '--' : this.$utils.label(o.message)
          })
          this.failNum = res.list.filter(i => { return i.state + '' === '1' }).length
          this.selList = []
          this.tableData = res.list
          this.pagination.rowsNumber = res.total
        }).finally(() => {
          this.$q.loading.hide()
          this.isTableLoading = false
        })
      }
    },
    resetSearch () {
      this.queryParams.sort = ['all']
      this.queryParams.status = 'all'
      this.queryParams.productId = null
      this.queryParams.timeRange = []
      this.queryParams.id = ''
      this.$refs.workShopSearch.initData()
    },
    // 查询按钮
    submit () {
      this.pagination.pageNum = 1
      // 无设备时直接清空列表不再请求
      if (this.queryParams.devices.length) {
        this.getList()
      } else {
        this.tableData = []
        this.pagination.rowsNumber = 0
      }
    }
  }
}
</script>

<style scoped>

</style>
